package io.github.l86400.component.selenium.core.web.driver.chrome;

import io.github.l86400.component.selenium.core.config.ChromeDriverConfig;
import io.github.l86400.util.bean.EmptyUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 86400
 * @since 2021/12/20 11:04
 */
public class ChromeOptions {
    public ChromeOptions() {

    }

    /**
     * 是否启用无头模式（后台允许）
     */
    private boolean headless = false;
    /**
     * 是否禁用gpu加速
     */
    private boolean disableGpb = false;
    /**
     * 加载图片
     */
    private boolean loadImg = true;
    /**
     * --no-sandbox
     */
    private boolean noSandbox = false;
    /**
     * 默认chrome 版本
     */
    private String chromeVersion = "96";

    public ChromeOptions noSandBox(boolean noSandbox) {
        this.noSandbox = noSandbox;
        return this;
    }

    public ChromeOptions noSandBox() {
        return noSandBox(true);
    }

    public ChromeOptions loadImg(boolean loadImg) {
        this.loadImg = loadImg;
        return this;
    }

    public ChromeOptions loadImg() {
        return loadImg(false);
    }

    public ChromeOptions setChromeVersion(String chromeVersion) {
        this.chromeVersion = chromeVersion;
        return this;
    }

    public ChromeOptions headless() {
        return headless(true);
    }

    public ChromeOptions headless(boolean headless) {
        this.headless = headless;
        return this;
    }

    public ChromeOptions disableGpb() {
        return disableGpb(true);
    }

    public ChromeOptions disableGpb(boolean disableGpb) {
        this.disableGpb = disableGpb;
        return this;
    }

    public org.openqa.selenium.chrome.ChromeOptions toChromeOptions() {
        ChromeDriverConfig.chromeDriver(this.chromeVersion);
        org.openqa.selenium.chrome.ChromeOptions chromeOptions = new org.openqa.selenium.chrome.ChromeOptions();
        chromeOptions.addArguments("--lang=zh-CN");
        chromeOptions.setHeadless(headless);
        if (disableGpb) {
            chromeOptions.addArguments("--disable-gpu");
        }
        if (noSandbox) {
            chromeOptions.addArguments("--no-sandbox");
        }
        Map<String, Object> prefsMap = new HashMap<>(1);
        if (!loadImg) {
            prefsMap.put("profile.managed_default_content_settings.images", 2);
        }
        if (!EmptyUtil.isEmpty(prefsMap)) {
            chromeOptions.setExperimentalOption("prefs", prefsMap);
        }
        return chromeOptions;
    }
}
